package cn.ddiancan.gateway.filter;

import java.util.List;

import cn.ddiancan.gateway.config.SsoConstants;
import cn.ddiancan.gateway.service.AuthenticationService;
import cn.ddiancan.xddcloud.common.constants.XddHeaderConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Slf4j
@RequiredArgsConstructor
@Component
public class LogoutFilter implements WebFilter, Ordered {

    private static final String CACHE_KEY = "xddcloud:" + XddHeaderConstant.PERMISSION_CACHE_PREFIX + "gateway:user:";

    private static final List<String> matchUrl = List.of("/**/logout", "/**/redis/clean");

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private final StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        // 登出接口，清理本地缓存
        ServerHttpRequest request = exchange.getRequest();
        if (matchUrl.stream().anyMatch(url -> antPathMatcher.match(url, request.getURI().getPath()))) {
            String accessToken = request.getHeaders().getFirst(SsoConstants.X_ACCESS_TOKEN);
            if (!StringUtils.hasText(accessToken)) {
                accessToken = request.getHeaders().getFirst(SsoConstants.USER_CODE);
            }
            if (StringUtils.hasText(accessToken)) {
                // 清除一级缓存
                AuthenticationService.getLevelOneCache().invalidate(accessToken);

                // 清除二级缓存
                String key = CACHE_KEY.concat(accessToken);
                if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
                    redisTemplate.delete(key);
                }
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
